﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace SocketControl
{
    [Serializable]
    public class ProtocolParket
    {
        public int LENGTH = 0;
        public byte[] buffer = new byte[BaseSocketControl.cache];

        /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static byte[] Serializable(ProtocolParket param)
        {
            byte[] buffer = null;
            IFormatter fs = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            fs.Serialize(ms, param);
            buffer = ms.GetBuffer();
            ms.Close();
            return buffer;
        }

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static ProtocolParket DeSerializable(byte[] buffer)
        {
            ProtocolParket obj = new ProtocolParket();
            try
            {
                MemoryStream ms = new MemoryStream(buffer);
                ms.Position = 0;
                IFormatter fs = new BinaryFormatter();
                obj = (ProtocolParket)fs.Deserialize(ms);
                ms.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return obj;
        }


        /// <summary>
        /// 装包
        /// </summary>
        /// <param name="buffer">buffer:byte[]</param>
        /// <returns>IList&lt;ProtocolParket&gt;</returns>
        public static IList<ProtocolParket> getPacket(byte[] buffer)
        {
            IList<ProtocolParket> result = new List<ProtocolParket>();
            if (buffer.Length > BaseSocketControl.cache)
            {
                for (int i = 0; i < buffer.Length; i += BaseSocketControl.cache)
                {
                    ProtocolParket parket = new ProtocolParket();
                    if (buffer.Length - i > BaseSocketControl.cache)
                    {
                        buffer.ToList().CopyTo(i, parket.buffer, 0, BaseSocketControl.cache);
                    }
                    else
                    {
                        buffer.ToList().CopyTo(i, parket.buffer, 0, buffer.Length - i);
                    }
                    parket.LENGTH = buffer.Length;
                    result.Add(parket);
                }
            }
            else
            {
                ProtocolParket tmpParket = new ProtocolParket();
                tmpParket.LENGTH = buffer.Length;
                tmpParket.buffer = buffer;
                result.Add(tmpParket);
            }
            return result;
        }
    }
}
